package com.lt.tccdemo.service;

import com.lt.tccdemo.db108.dao.AccountAMapper;
import com.lt.tccdemo.db108.dao.SendMessageMapper;
import com.lt.tccdemo.db108.model.AccountA;
import com.lt.tccdemo.db108.model.SendMessage;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

import static org.apache.rocketmq.client.producer.SendStatus.SEND_OK;

/**
 * @author lucine
 * @version 1.0 2021/10/5 15:25
 */
@Service
public class PaymentService {

    @Autowired
    private AccountAMapper accountAMapper;

    @Autowired
    private SendMessageMapper sendMessageMapper;

    @Autowired
    private DefaultMQProducer defaultMQProducer;


    /**
     * 支付接口(消息队列)
     * @param userId
     * @param orderId
     * @param amount
     * @return  0成功 1用户不存在 2余额不足
     */
    @Transactional(transactionManager = "xm108", rollbackFor = Exception.class)
    public  int paymentMQ(int userId, int orderId, BigDecimal amount) throws Exception {
        //根据用户id，找出用户信息
        AccountA accountA = accountAMapper.selectByPrimaryKey(userId);
        //如果用户不存在返回1
        if(accountA==null){
            return 1;
        }
        //如果用户余额不足返回2
        if(accountA.getBalance().compareTo(amount) <0){
            return 2;
        }
        accountA.setBalance(accountA.getBalance().subtract(amount));
        //扣减金额
        accountAMapper.updateByPrimaryKey(accountA);

        Message message = new Message();
        message.setTopic("payment");
        message.setKeys(orderId+"");
        message.setBody("订单已支付".getBytes());
        try{
            SendResult send = defaultMQProducer.send(message);
            SendStatus sendStatus = send.getSendStatus();
            if(sendStatus == SendStatus.SEND_OK){
                return 0;
            }else {
                //向外抛出异常，让账户进行回滚
                throw new Exception("消息发送失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            //向最外层抛出异常，让账户进行回滚
            throw e;
        }
    }


    /**
     * 支付接口
     * @param userId
     * @param orderId
     * @param amount
     * @return  0成功 1用户不存在 2余额不足
     */
    @Transactional(transactionManager = "xm108", rollbackFor = Exception.class)
    public  int payment(int userId, int orderId, BigDecimal amount){
        //根据用户id，找出用户信息
        AccountA accountA = accountAMapper.selectByPrimaryKey(userId);
        //如果用户不存在返回1
        if(accountA==null){
            return 1;
        }
        //如果用户余额不足返回2
        if(accountA.getBalance().compareTo(amount) <0){
            return 2;
        }
        accountA.setBalance(accountA.getBalance().subtract(amount));
        //扣减金额
        accountAMapper.updateByPrimaryKey(accountA);

        SendMessage sendMessage = new SendMessage();
        sendMessage.setOrderId(orderId);
        //未发送
        sendMessage.setStatus(0);
        //失败次数
        sendMessage.setFalureCnt(0);
        sendMessage.setCreateTime(new Date());
        sendMessage.setCreateUser(userId);
        sendMessage.setUpdateTime(new Date());
        sendMessage.setUpdateUser(userId);

        sendMessageMapper.insertSelective(sendMessage);

        return 0;
    }

}
